﻿/*************************************************************************************
 *
 * 文 件 名:   ConvertParse_30Wor50W_Digit50W_Impl
 * 描    述: 
 * 
 * 版    本：  V1.0
 * 创 建 者：  YSW 
 * 创建时间：  2021-09-09 16:02:38
 * ======================================
 * 历史更新记录
 * 版本：V          修改时间：         修改人：
 * 修改内容：
 * ======================================
*************************************************************************************/

using CommonModel.Model;
using CommonModel.Util;
using GXRTBTC.PublicClassLibrary.Field;
using GXRTBTC.PublicClassLibrary.Interface;
using GXRTBTC.PublicClassLibrary.Util;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GXRTBTC.PublicClassLibrary.ParseImpl
{
    public class ConvertParse_ByteParseToHeadDigitTransmitter300_Impl : IConvertParse
    {
        public string mVersion { get; } = "ConvertParse_ByteParseToHeadDigitTransmitter300_Impl";
        public Dictionary<string, SchemaDocument> schemaDict { get; set; }
        /// <summary>
        /// 未知，无法解析的
        /// </summary>
        public Dictionary<string, int> unknownSchemaName { get; set; } = new Dictionary<string, int>();

        public ConvertParse_ByteParseToHeadDigitTransmitter300_Impl()
        { 
        
        }

        /// <summary>
        /// 转换解析
        /// </summary>
        /// <param name="packetInfo"></param>
        /// <returns></returns>
        public Dictionary<string, object> DataConvert(PacketInfo packetInfo)
        {
            Dictionary<string, object> parsedDataDictionary;
            byte[] data = TransForm.HexTobyte(packetInfo.reviceDatas);

            //头信息
            HeaderData header = packetInfo.header;
            if (header == null)
            {
                packetInfo.tipMsg = "帧头异常";
                return null;
            }

            //拼接配置名称
            string schemaName;
            if (header.device.Equals("0x00") || header.device.Equals("0x0703") || header.device.Equals("0x0401"))
            {
                schemaName = header.device + "_" + header.vendor + "_" + header.msgType;
            }
            else
            {
                schemaName = header.device + "_" + header.vendor + "_" + header.hardware + "_" + header.software + "_" + header.msgType;
            }

            SchemaDocument doc;
            if (schemaDict.ContainsKey(schemaName))
            {
                if (unknownSchemaName.ContainsKey(schemaName))
                {
                    unknownSchemaName.Remove(schemaName);
                }

                doc = schemaDict[schemaName];// 获取对应的xml解析文件
                //关联配置，精简schemaDict的空间占用
                if (doc.rname != null && !"".Equals(doc.rname))
                {
                    if (schemaDict.ContainsKey(doc.rname))
                    {
                        doc = schemaDict[doc.rname];// 获取对应的xml解析文件
                    }
                    else
                    {
                        if (!unknownSchemaName.ContainsKey(doc.rname))
                        {
                            unknownSchemaName.TryAdd(doc.rname, 0);
                        }
                        packetInfo.tipMsg = "解析协议配置【" + doc.rname + "】未找到，请检查file_param_main表";
                        return null;
                    }
                }

                if (doc.msgType.Equals("struct"))
                {
                    parsedDataDictionary = StructUtil.ByteParseViaStruct(doc, data, header.bodybegin);
                }
                else
                {
                    //300W/1000W的
                    parsedDataDictionary = CodeUtil.ByteParseViaCode(doc, data, "M_300_1000");
                }
            }
            else
            {
                //CommonUtil.mLogger.LogError("获取解析协议配置失败, 应该获取的协议名称: " + schemaName);
                if (!unknownSchemaName.ContainsKey(schemaName))
                {
                    unknownSchemaName.TryAdd(schemaName, 0);
                }
                packetInfo.tipMsg = "解析协议配置【" + schemaName + "】未找到，请检查file_param_main表";
                return null;
            }

            //拼接发送的json数据
            Dictionary<string, object> resultDict = new Dictionary<string, object>();//发送下去的总json数据

            Dictionary<string, string> ptlDict = new Dictionary<string, string>();
            ptlDict.Add("ptlver", mVersion);
            ptlDict.Add("ts", Convert.ToInt64(TransForm.GetTimeStamp(packetInfo.receivingTime)).ToString());//时间戳
            ptlDict.Add("ptlnode", "");//协议转换节点
            ptlDict.Add("file_name", doc.file_name);//配置文件名称
            ptlDict.Add("schemaName", schemaName);//对应的协议文档名字

            Dictionary<string, string> addDict = new Dictionary<string, string>();
            addDict.Add("ip", packetInfo.ip);//ip地址
            addDict.Add("port", packetInfo.port.ToString());//端口
            if (header.stationcode == null)
            {
                addDict.Add("sid", "");//台站id
            }
            else
            {
                addDict.Add("sid", header.stationcode);//台站id
            }
            addDict.Add("paramId", doc.id);

            resultDict.Add("ptlinfo", ptlDict);
            resultDict.Add("addr", addDict);
            resultDict.Add("datas", parsedDataDictionary);

            return resultDict;
        }

        /// <summary>
        /// 获取数据头
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public HeaderData GetHeaderData(PacketInfo packetInfo)
        {
            //开头是AA
            //其它条件，第三字节为0x41，才是主动上报数据指令
            byte[] data = TransForm.HexTobyte(packetInfo.reviceDatas);
            HeaderData header = HeaderUtil.ByteParseToHeadDigitTransmitter300(data);

            if (null == header || header.errorFlag.Equals("yes"))
            {
                CommonUtil.mLogger.LogError("0xaa解析后的header是空的");
                packetInfo.tipMsg = "0xaa解析后的header是空的";
                return header;
            }

            HeaderUtil.DecorateHead(header);//修正帧头数据
            //增加header信息获取厂家为空时的判断
            if (null == header.vendor || header.vendor.Equals("技术中心"))
            {
                header.vendor = "0x0000";
            }

            if (header.vendor.Contains("成都德芯"))
            {
                header.vendor = "0x0006";
            }

            header.classVer = this.mVersion;
            return header;
        }

        public void Dispose()
        {

        }
    }
}
